package com.lanou.zy.projecta.activity;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.google.gson.Gson;
import com.lanou.zy.projecta.R;
import com.lanou.zy.projecta.adapter.SearchRecyclerViewAdapter;
import com.lanou.zy.projecta.adapter.SearchResultRecyclerViewAdapter;
import com.lanou.zy.projecta.entity.HotSearch;
import com.lanou.zy.projecta.entity.SearchResult;
import com.lanou.zy.projecta.fragment.SearchResultFragment;
import com.lanou.zy.projecta.util.OnItemClickListener;
import com.lanou.zy.projecta.util.StringUtil;

import java.util.List;

public class SearchActivity extends AppCompatActivity implements View.OnClickListener {
    private RecyclerView searchRecyclerView, searchPopWindowRecyclerView;
    private SearchRecyclerViewAdapter searchRecyclerViewAdapter;
    private SearchResultRecyclerViewAdapter searchResultRecyclerViewAdapter;
    private RequestQueue queue;
    private EditText searchBringIn_Et;
    private String keyword;
    private PopupWindow pw;
    private ImageView searchBackToRecommend_Iv;
    private HotSearch h;
    private FrameLayout searchResuslt_Frm, replacedFrm;
    private FragmentManager manager = getSupportFragmentManager();
    private SearchResult s;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        initData();
    }

    private void initView() {
        searchBringIn_Et = (EditText) findViewById(R.id.searchBringIn_Et);
        searchBringIn_Et.addTextChangedListener(textWatcher);
        searchBackToRecommend_Iv = (ImageView) findViewById(R.id.searchBackToRecommend_Iv);
        searchBackToRecommend_Iv.setOnClickListener(this);
        searchResuslt_Frm = (FrameLayout) findViewById(R.id.searchResuslt_Frm);
        replacedFrm = (FrameLayout) findViewById(R.id.replacedFrm);

        // 搜索前的recyclerview
        searchRecyclerViewAdapter = new SearchRecyclerViewAdapter();
        searchRecyclerView = (RecyclerView) findViewById(R.id.searchRecyclerView);

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 1);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        searchRecyclerView.setLayoutManager(gridLayoutManager);
        searchRecyclerView.setAdapter(searchRecyclerViewAdapter);

        searchRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {

            /**
             * 点击热门搜索的监听事件
             * 得到点击的具体字符串
             * 将字符串传递到新生成的Fragment中，并进行Fragment的切换
             * 最后将Edittext设置为被点击的字符串 隐藏弹出窗口
             * */
            @Override
            public void onItemClick(View view, int position) {
                String name = h.getData().get(position);

                Bundle bundle = new Bundle();
                bundle.putString("name", name);

                manager.beginTransaction().replace(R.id.replacedFrm, SearchResultFragment.newInstance(name)).commitAllowingStateLoss();

                searchBringIn_Et.setText(name);
                replacedFrm.setVisibility(View.VISIBLE);
                searchResuslt_Frm.setVisibility(View.GONE);
                pw.dismiss();
//                searchRecyclerView.setVisibility(View.GONE);

            }

            @Override
            public void onItemLongClick(View view, int position) {
            }
        });

        // 整个搜索界面的recyclerview头布局
        RecyclerViewHeader searchHeader = (RecyclerViewHeader) findViewById(R.id.searchHeader);
        searchHeader.attachTo(searchRecyclerView, true);

    }

    /**
     * 拉取热门搜索的数据
     */
    private void initData() {
        queue = Volley.newRequestQueue(this);
        String url = "http://open.qyer.com/qyer/search/hot_history?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=863811018458956&track_app_version=6.8.1&track_app_channel=taobao&track_device_info=msm8960&track_os=Android4.2.2&app_installtime=1445235475313&lat=38.883734&lon=121.544912";
        StringRequest requestIn = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                h = gson.fromJson(response, HotSearch.class);
                List<String> str = h.getData();
                searchRecyclerViewAdapter.addData(str);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        queue.add(requestIn);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.searchBackToRecommend_Iv:
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                overridePendingTransition(R.anim.left_in, R.anim.right_out);
                finish();
                break;
        }
    }

    /**
     * 将键入的信息进行搜索
     */
    public void getResult() {
        String path = "http://open.qyer.com/qyer/search/autocomplate?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=863811018458956&track_app_version=6.8.1&track_app_channel=taobao&track_device_info=msm8960&track_os=Android4.2.2&app_installtime=1445235475313&lat=38.883734&lon=121.544912&keyword=" + keyword;
        StringRequest requestOut = new StringRequest(path, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                s = gson.fromJson(response, SearchResult.class);
                SearchResult.DataEntity sd = s.getData();
                List<SearchResult.DataEntity.EntryEntity> sde = sd.getEntry();
                searchResultRecyclerViewAdapter.addData(sde);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        queue.add(requestOut);
    }

    /**
     * 弹出搜索结果的窗口
     */
    private void showPopupWindow(View v) {
        pw = new PopupWindow(this);

        View view = getLayoutInflater().inflate(R.layout.search_popwindow, null);
        searchPopWindowRecyclerView = (RecyclerView) view.findViewById(R.id.searchPopWindowRecyclerView);

        pw.setContentView(view);
        pw.setWidth(500);
        pw.setHeight(700);
        pw.setBackgroundDrawable(getResources().getDrawable(R.drawable.all_white));

        pw.setOutsideTouchable(false);
        pw.showAsDropDown(v);
    }

    public void PopupViewCreate() {
        // 搜索后弹出窗口的recyclerView
        searchResultRecyclerViewAdapter = new SearchResultRecyclerViewAdapter();
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 1);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        searchPopWindowRecyclerView.setLayoutManager(gridLayoutManager);
        searchPopWindowRecyclerView.setAdapter(searchResultRecyclerViewAdapter);
        searchResultRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {

            /**
             * 点击之后隐藏热门搜索的framlayout，显示带tablayout的framlayout
             * */
            @Override
            public void onItemClick(View view, int position) {
                String name = s.getData().getEntry().get(position).getCnname();
                Bundle args = new Bundle();
                args.putString("name", name);
                manager.beginTransaction().replace(R.id.replacedFrm, SearchResultFragment.newInstance(name)).commitAllowingStateLoss();

                searchBringIn_Et.setText(name);
                replacedFrm.setVisibility(View.VISIBLE);
                searchResuslt_Frm.setVisibility(View.GONE);
                pw.dismiss();
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }


    /**
     * 定义一个变量 记录弹出窗口的状态，如果edittext的输入全部删除的时候，隐藏窗口
     * 防止弹出多个窗口
     */
    private boolean flag = true;
    private TextWatcher textWatcher = new TextWatcher() {

        /**
         * 对dittext进行监听
         * */
        @Override
        public void afterTextChanged(Editable s) {

            String str = searchBringIn_Et.getText().toString().trim();
            keyword = StringUtil.utf8Encode(str);

            if (str != null && str.length() > 0) {

                if (flag == true) {
                    showPopupWindow(searchBringIn_Et);
                    replacedFrm.setVisibility(View.GONE);
                    searchResuslt_Frm.setVisibility(View.VISIBLE);
                }

                getResult();

                if (flag == true) {
                    PopupViewCreate();
                    flag = false;
                }

            }  else {
                pw.dismiss();
                replacedFrm.setVisibility(View.GONE);
                searchResuslt_Frm.setVisibility(View.VISIBLE);
                flag = true;
            }
            if (pw.isShowing()) {
                replacedFrm.setVisibility(View.GONE);
                searchResuslt_Frm.setVisibility(View.GONE);
            }

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
        }
    };

}
